package servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.alibaba.fastjson.JSONObject;

import domain.Account;
import service.AccountServiceImpl;
import service.IAccountService;


/**
 * Servlet implementation class LoginServlet
 */
public class LoginServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

    /**
     * Default constructor. 
     */
    public LoginServlet() {
        // TODO Auto-generated constructor stub
    }
    private IAccountService service;

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		response.getWriter().append("Served at: ").append(request.getContextPath());
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
	String name=request.getParameter("user.name");
	String pass=request.getParameter("user.pwd");
	service=new AccountServiceImpl();
	Map<String,String> resultMap= new HashMap<String,String>();
	 try {
		 if (name!=null && pass!=null) {
			 Account lAccount=service.login(name, pass);
			 if (lAccount!=null) {
				 request.getSession().setAttribute("luser", lAccount);
				 resultMap.put("success", "true");
				 resultMap.put("msg", "登陆成功");
			String jsonObject = JSONObject.toJSONString(resultMap);
				 PrintWriter out =  response.getWriter();
				 out.write(jsonObject);
			 }
		}else {
			resultMap.put("success", "false");
			 resultMap.put("msg", "登陆失败");
		}
	} catch (Exception e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	}
	}

	
}
